﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebAPI_DEMO.Models;
using static WebAPI_DEMO.Service.JWTService;

namespace WebAPI_DEMO.Service
{
    /// <summary>
    /// 认证处理服务
    /// </summary>
    public class JWTService : IJWTService
    {
        /// <summary>
        /// JWT配置信息
        /// </summary>
        private readonly JWTConfig _jwtConfig;

        /// <summary>
        /// 通过构造注入 JWT配置信息
        /// </summary>
        /// <param name="jwtConfig"></param>
        public JWTService(IOptions<JWTConfig> jwtConfig)
        {
            this._jwtConfig = jwtConfig.Value;
        }
        /// <summary>
        /// 实现接口方法 创建Token
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string CreateToken(string name, int userId)
        {
            //登录信息的载荷 
            //把有需要的信息写到Token
            var claims = new[] {
                //预定义好的类型
                //用户Id
                new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
                //用户名
                new Claim(ClaimTypes.Name, name),
                new Claim(ClaimTypes.Email,""),
                new Claim(ClaimTypes.MobilePhone,""),
                //设置自定义载荷体类型
                new Claim("QQ","")

            };

            //创建密钥类
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.Secret));
            //密钥加密
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //token配置 创建TOKEN配置
            var jwtToken = new JwtSecurityToken(_jwtConfig.Issuer,
                _jwtConfig.Audience,
                claims,
                //          当前时间+多少分钟（AccessExpiration）
                expires: DateTime.Now.AddMinutes(_jwtConfig.AccessExpiration),
                signingCredentials: credentials);

            //获取token 
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return token;
        }
    }
}
